<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="营业时间" prop="businessHours">
              <el-input v-model="queryParams.businessHours" placeholder="请输入营业时间" clearable @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="queryParams.phone" placeholder="请输入联系电话" clearable @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item label="地址" prop="address">
              <el-input v-model="queryParams.address" placeholder="请输入地址" clearable @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item label="城市" prop="city">
              <el-input v-model="queryParams.city" placeholder="请输入城市" clearable @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['app:SkShop:add']">新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
                       v-hasPermi="['app:SkShop:edit']">修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
                       v-hasPermi="['app:SkShop:remove']">删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['app:SkShop:export']">
              导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="SkShopList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="ID" align="center" prop="id" width="120" v-if="true"/>
        <el-table-column label="封面" align="center" prop="cover" width="170">
          <template #default="scope">
            <image-preview :src="scope.row.cover" :width="150" :height="80"/>
          </template>
        </el-table-column>
        <el-table-column label="标题" align="center" prop="title" width="150"/>
        <el-table-column label="营业时间" align="center" prop="businessHours" width="120"/>
        <el-table-column label="联系电话" align="center" prop="phone" width="120"/>
        <el-table-column label="评分" align="center" prop="phone" width="120">
          <template #default="scope">
            <div  style="display: flex">
              <div v-for="item in 5">
                <el-icon color="#ffe200" v-if="scope.row.score>=item"><Star/></el-icon>
                <el-icon v-else ><Star/></el-icon>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="标签" align="center" prop="tag" width="180">
          <template #default="scope">
            <el-tag style="margin-right: 5px;margin-bottom:5px" v-if="scope.row.tag" v-for="item in scope.row.tag.split(' ')" type="primary">{{item}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="人均消费" align="center" prop="price"/>
        <el-table-column label="地址" width="180" align="center" prop="address"/>
        <el-table-column label="是否推荐" align="center" prop="isTj">
          <template #default="scope">
            <el-tag v-if="scope.row.isTj==1" type="primary">是</el-tag>
            <el-tag v-else type="info">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="推荐编号" align="center" prop="sort"/>
        <el-table-column label="经度" align="center" prop="longitude" width="100"/>
        <el-table-column label="纬度" align="center" prop="latitude" width="100"/>
        <el-table-column label="城市" align="center" prop="city"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="120">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                         v-hasPermi="['app:SkShop:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                         v-hasPermi="['app:SkShop:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="设为推荐" placement="top">
              <el-button link type="primary" icon="Discount" @click="handleOpen(scope.row)"
                         v-hasPermi="['app:SkShop:edit']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                  v-model:limit="queryParams.pageSize" @pagination="getList"/>
    </el-card>
    <!-- 添加或修改商家信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="SkShopFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="封面" prop="cover">
          <image-upload v-model="form.cover" :limit="1"/>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-checkbox-group v-model="listTypeYx">
            <el-checkbox v-for="item in typeList" :label="item.name" :value="item.name" />
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="约玩项目" prop="project">
          <el-checkbox-group v-model="listProjectYx">
            <el-checkbox v-for="item in yue_wan_project" :label="item.label" :value="item.label" />
          </el-checkbox-group>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商店名称" prop="title">
              <el-input v-model="form.title" placeholder="请输入商店名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="营业时间" prop="businessHours">
              <el-input v-model="form.businessHours" placeholder="请输入营业时间"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="城市区号" prop="city">
              <el-input v-model="form.city" placeholder="请输入城市例如临沂的是0539"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="评分" prop="score">
              <el-input v-model="form.score" placeholder="请输入评分1~5，满分5分" type="number"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="人均消费" prop="price">
              <el-input v-model="form.price" type="number" placeholder="请输入人均消费"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="标签" prop="title">
          <el-input v-model="form.tag" placeholder="请输入标签，多个标签空格隔开"/>
        </el-form-item>
        <el-form-item label="榜单说明" prop="bdTitle">
          <el-input v-model="form.bdTitle" placeholder="标签"/>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址"/>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input v-model="form.longitude" placeholder="请输入经度"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude">
              <el-input v-model="form.latitude" placeholder="请输入纬度"/>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="app-container" style="position: relative;">
          <div style="background-color: #ffffff;">
            <el-input
              class="input_ditu"
              style=""
              id="tipinput"
              v-model="searchKeyword"
              placeholder="请输入地址回车键搜索"
              clearable
              @keyup.enter="sosuuoseach"
            ></el-input>
            <div id="container" style="width: 700px;height: 250px;z-index: 2"></div>

          </div>
        </div>
<!--        <el-form-item label="介绍">-->
<!--          <editor v-model="form.content" :min-height="192"/>-->
<!--        </el-form-item>-->
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="dialogVisible"
      title="推荐商家"
      width="500"
      :before-close="handleClose"
    >
      <div><span>序号：</span>
        <el-input v-model="form.sort" type="number" style="width: 240px" placeholder="请输入推荐排序编号" />
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="funHandleClose">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style>
.input_ditu {
  z-index: 99999999;
  width: 300px;
  margin-right: 10px;
  background-color: #fff;
  margin-top: 10px;
  position: absolute;
  float: left;

}
</style>
<script setup name="SkShop" lang="ts">
import {listSkShop, getSkShop, delSkShop, addSkShop, updateSkShop} from '@/api/app/SkShop';
import {
  allOneList
} from '@/api/app/SkYueJuType';
import {SkShopVO, SkShopQuery, SkShopForm} from '@/api/app/SkShop/types';
import AMapLoader from '@amap/amap-jsapi-loader';

const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const dialogVisible = ref(false);
const info = ref({});
const SkShopList = ref<SkShopVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const placeSearchComponent = ref();
const searchKeyword = ref('');
const AMapAll = ref();
const typeList = ref([]);
const listTypeYx = ref([]);
const listProjectYx = ref([]);

const queryFormRef = ref<ElFormInstance>();
const SkShopFormRef = ref<ElFormInstance>();
const { yue_wan_project } = toRefs<any>(proxy?.useDict('yue_wan_project'));

const mapDiTu = ref();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: SkShopForm = {
  id: undefined,
  cover: undefined,
  businessHours: undefined,
  phone: undefined,
  address: undefined,
  longitude: undefined,
  latitude: undefined,
  content: undefined,
  city: undefined,
  isTj: undefined,
  sort: undefined
}
const data = reactive<PageData<SkShopForm, SkShopQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    cover: undefined,
    businessHours: undefined,
    phone: undefined,
    address: undefined,
    longitude: undefined,
    latitude: undefined,
    content: undefined,
    city: undefined,
    params: {}
  },
  rules: {
    id: [
      {required: true, message: "ID不能为空", trigger: "blur"}
    ],
    cover: [
      {required: true, message: "封面不能为空", trigger: "blur"}
    ],
    businessHours: [
      {required: true, message: "营业时间不能为空", trigger: "blur"}
    ],
    phone: [
      {required: true, message: "联系电话不能为空", trigger: "blur"}
    ],
    address: [
      {required: true, message: "地址不能为空", trigger: "blur"}
    ],
    longitude: [
      {required: true, message: "经度不能为空", trigger: "blur"}
    ],
    latitude: [
      {required: true, message: "纬度不能为空", trigger: "blur"}
    ],
    city: [
      {required: true, message: "城市不能为空", trigger: "blur"}
    ]
  }
});

const {queryParams, form, rules} = toRefs(data);
//打开推荐
const handleOpen=async (info) => {
  info.value = info
  reset();
  const res = await getSkShop(info.id);
  Object.assign(form.value, res.data);
  form.value.isTj = 1
  dialogVisible.value = true
}
//关闭推荐
const handleClose = async () => {
  dialogVisible.value = false
}
//关闭推荐
const funHandleClose = async () => {
  await updateSkShop(form.value).finally(() => buttonLoading.value = false);
  dialogVisible.value = false
  await getList();
}
/** 查询商家信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listSkShop(queryParams.value);
  SkShopList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  listTypeYx.value = []
  listProjectYx.value = []
  SkShopFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: SkShopVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加商家信息";
  nextTick(() => {
    initMap()
  })
}

/** 修改按钮操作 */
const handleUpdate = async (row?: SkShopVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getSkShop(_id);
  Object.assign(form.value, res.data);
  console.log(form.value.type)
  if (form.value.type!=null && form.value.type!=undefined){
    listTypeYx.value = JSON.parse(form.value.type)
  }
  if (form.value.project!=null && form.value.project!=undefined){
    listProjectYx.value = JSON.parse(form.value.project)
  }

  dialog.visible = true;
  dialog.title = "修改商家信息";
  nextTick(() => {
    initMap()
  })
}

/** 提交按钮 */
const submitForm = () => {
  if (listTypeYx.value.length>0){
    form.value.type = JSON.stringify(listTypeYx.value);
  }
  if (listProjectYx.value.length>0){
    form.value.project = JSON.stringify(listProjectYx.value);
  }
  SkShopFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateSkShop(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addSkShop(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      dialogVisible.value = false
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: SkShopVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除商家信息编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delSkShop(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}
const getTypeList = async () => {
  loading.value = true;
  const res = await allOneList();
  typeList.value = res.data
}
/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('app/SkShop/export', {
    ...queryParams.value
  }, `SkShop_${new Date().getTime()}.xlsx`)
}

//加在地图
const initMap = () => {
  const AMap = AMapAll.value;
  mapDiTu.value = new AMap.Map("container", {  //设置地图容器id
    viewMode: "3D",    //是否为3D地图模式
    zoom: 13,           //初始化地图级别
    zIndexOf:1
  });
  if (form.value.latitude){
    addMarker({lat: form.value.latitude, lng: form.value.longitude});
  }
  //点击事件
  mapDiTu.value.on('click', (event) => {
    const {lnglat, pixel} = event;
    console.log('经纬度:', lnglat.lng, lnglat.lat);
    console.log('像素位置:', pixel.x, pixel.y);
    addMarker(lnglat)
    selectAddress(lnglat)
  });

  function addMarker(lnglat) {
    mapDiTu.value.clearMap();
    form.value.latitude = lnglat.lat
    form.value.longitude = lnglat.lng
    const marker = new AMap.Marker({
      position: new AMap.LngLat(lnglat.lng, lnglat.lat), // 位置
      map: mapDiTu.value, // 指定地图
    });
    marker.setMap(mapDiTu.value);
  }

  //查询具体位置
  function selectAddress(lnglat) {
    var geocoder = new AMap.Geocoder({})
    geocoder.getAddress(lnglat, function (status, result) {
        if (status === 'complete' && result.info === 'OK') {
          form.value.address = result.regeocode.formattedAddress
          console.log('有经纬度对应的具体地址吗', result.regeocode.formattedAddress);
        } else {
          console.log('根据经纬度查询地址失败了', status, result);
        }
      }
    )
  }
}


function sosuuoseach() {
  // 注册placeSearch组件
  const AMap = AMapAll.value
  const search = new AMap.PlaceSearch({
    map: mapDiTu.value
  })
  console.log(search.search(form.value.address, (w, e) => {
    console.log(e)
  }))
}

onMounted(() => {
  window._AMapSecurityConfig = {
    securityJsCode: '4798abb27f815844db4780abbb3c3be5',
  }
  AMapLoader.load({
    key: "8145de4fb7d9e67f7ccda5855c15bd3f", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ['AMap.Geolocation', 'AMap.MouseTool', 'AMap.PlaceSearch', 'AMap.Geocoder'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  }).then((AMap) => {
    AMapAll.value = AMap;
  }).catch(e => {
    console.log(e);
  })
  getList();
  getTypeList()
});
</script>
